import {
  Geometry,
  Mesh,
  ShaderMaterial,
  TSVector2,
  TextureLoader,
  TwinSpace2D,
} from "twinspace2d";
import movePointerFrag from "./shader/movePointer.frag";
import movePointerVert from "./shader/movePointer.vert";
import tex from "./demo1.png";

const T2D = new TwinSpace2D("view2d");

const geometry = new Geometry();

const width = T2D.canvas.clientWidth;
const height = T2D.canvas.clientHeight;
geometry.setAttribute(
  "position",
  new Float32Array([
    0,
    0,
    width,
    0,
    width,
    height,
    width,
    height,
    0,
    height,
    0,
    0,
  ]),
  2
);

geometry.setAttribute(
  "uv",
  new Float32Array([0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0]),
  2
);

const material = new ShaderMaterial({
  uniforms: {
    u_resolution: {
      value: new TSVector2(T2D.canvas.clientWidth, T2D.canvas.clientHeight),
    },
    map: {
      value: new TextureLoader().load(tex, (map) => {}),
    },
    mouseMove: {
      value: new TSVector2(0, 0),
    },
    u_radio: {
      value: new TSVector2(
        T2D.canvas.clientWidth / width,
        T2D.canvas.clientHeight / height
      ),
    },
  },
  fragmentShader: movePointerFrag,
  vertexShader: movePointerVert,
});

const mesh = new Mesh(geometry, material);

T2D.scene.add(mesh);

window.addEventListener("resize", () => {
  material.uniforms.u_resolution.value = new TSVector2(
    T2D.canvas.clientWidth,
    T2D.canvas.clientHeight
  );
  material.uniforms.u_radio.value = new TSVector2(
    T2D.canvas.clientWidth / width,
    T2D.canvas.clientHeight / height
  );
});

window.addEventListener("mousemove", (event) => {
  material.uniforms.mouseMove.value = new TSVector2(
    event.clientX,
    event.clientY
  );
});

const render = () => {
  requestAnimationFrame(render);
  T2D.render();
};

render();
